/**
 * System Prompt模板引擎
 * 用于渲染角色的System Prompt模板
 */

import { PromptTemplate } from './types'

/**
 * Prompt模板引擎
 */
export class PromptTemplateEngine {
  /**
   * 渲染模板，替换变量占位符
   */
  render(template: string, variables: Record<string, any>): string {
    let result = template

    // 替换 {{variable}} 格式的占位符
    result = result.replace(/\{\{(\w+)\}\}/g, (match, key) => {
      const value = variables[key]
      if (value !== undefined) {
        return String(value)
      }
      console.warn(`[Prompt模板引擎] 未找到变量: ${key}`)
      return match  // 保留原占位符
    })

    // 替换 {variable} 格式的占位符（兼容性）
    result = result.replace(/\{(\w+)\}/g, (match, key) => {
      const value = variables[key]
      if (value !== undefined) {
        return String(value)
      }
      return match
    })

    return result.trim()
  }

  /**
   * 验证模板格式是否正确
   */
  validateTemplate(template: string): {
    isValid: boolean
    errors: string[]
    variables: string[]
  } {
    const errors: string[] = []
    const variables: string[] = []

    // 提取所有变量
    const variableMatches = template.match(/\{\{(\w+)\}\}/g) || []
    for (const match of variableMatches) {
      const variable = match.replace(/\{\{|\}\}/g, '')
      if (!variables.includes(variable)) {
        variables.push(variable)
      }
    }

    // 检查括号配对
    const openBrackets = (template.match(/\{\{/g) || []).length
    const closeBrackets = (template.match(/\}\}/g) || []).length
    if (openBrackets !== closeBrackets) {
      errors.push('模板中的双大括号不匹配')
    }

    // 检查嵌套问题
    if (template.includes('{{{') || template.includes('}}}')) {
      errors.push('不支持三重大括号或嵌套')
    }

    return {
      isValid: errors.length === 0,
      errors,
      variables
    }
  }

  /**
   * 从模板中提取所需变量列表
   */
  extractVariables(template: string): string[] {
    const variables = new Set<string>()
    
    // 提取 {{variable}} 格式的变量
    const matches = template.match(/\{\{(\w+)\}\}/g) || []
    for (const match of matches) {
      const variable = match.replace(/\{\{|\}\}/g, '')
      variables.add(variable)
    }

    return Array.from(variables)
  }

  /**
   * 检查变量是否完整提供
   */
  checkVariables(template: string, variables: Record<string, any>): {
    missing: string[]
    unused: string[]
    complete: boolean
  } {
    const required = this.extractVariables(template)
    const provided = Object.keys(variables)

    const missing = required.filter(v => !(v in variables))
    const unused = provided.filter(v => !required.includes(v))

    return {
      missing,
      unused,
      complete: missing.length === 0
    }
  }
}

/**
 * 默认的模板引擎实例
 */
export const promptTemplateEngine = new PromptTemplateEngine()